/**
 * grayrabbit Inc.
 * Copyright (c) 2011-2012 All Rights Reserved.
 */
package com.grayrabbit.slacker.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.grayrabbit.slacker.constant.ConfigConstant;

/**
 * 模板文件管理
 * 
 * @author liyd
 * @version $Id: TemplateFileProvider.java, v 0.1 2012-5-9 下午5:57:07 liyd Exp $
 */
public class TemplateFileProvider {

    /** 日志对象 */
    private final static Logger        LOG     = Logger.getLogger(TemplateFileProvider.class);

    /** 存放模板文件，读取到的字符串的形式 */
    private static Map<String, String> fileMap = new HashMap<String, String>();

    /**
     * 判断文件是否存在
     * 
     * @param filePath 文件路径
     * @return
     */
    public static boolean isFileExists(String filePath) {

        File file = new File(filePath);

        if (file.exists()) {
            return true;
        }

        return false;

    }

    /**
     * 得到模板文件
     * 
     * @param templateName
     * @return
     */
    public static synchronized String getTemplate(String templateName) {

        String filePath = null;
        try {

            if (fileMap.get(templateName) != null) {

                return fileMap.get(templateName);
            }

            String encoding = "GBK";
            if (ConfigConstant.ENCODING != null && !"".equals(ConfigConstant.ENCODING)) {
                encoding = ConfigConstant.ENCODING;
            }

            BufferedReader bfReader = new BufferedReader(new InputStreamReader(
                TemplateFileProvider.class.getClassLoader().getResourceAsStream(templateName),
                encoding));

            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bfReader.readLine()) != null) {

                sb.append(line);
                sb.append("\r\n");

            }

            fileMap.put(templateName, new String(sb.toString().getBytes(encoding), encoding));

        } catch (IOException e) {
            LOG.error("读取模板文件失败[vm=" + filePath + "]", e);
        }

        return fileMap.get(templateName);
    }

    /**
     * 写入生成的代码文件
     * 
     * @param filePath
     * @param source
     */
    public static void writeFile(String filePath, String source) {

        try {
            File targetFile = new File(filePath);
            File targetDir = new File(filePath.substring(0, filePath.lastIndexOf("/")));
            if (!targetDir.exists())
                targetDir.mkdirs();
            FileWriter targetFileWriter = new FileWriter(targetFile);
            targetFileWriter.write(source);
            targetFileWriter.close();

            LOG.info("生成文件：" + targetFile.getAbsoluteFile());
        } catch (IOException e) {
            LOG.error("生成代码文件失败", e);
        }
    }

}
